package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmAutoScanService;
import com.heima.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author 陈辉
 * @data 2023 17:46
 */
@Service
@Slf4j
public class WmTaskServiceImpl implements WmTaskService {

    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmAutoScanService wmAutoScanService;

    /**
     * 添加审核文章的任务
     *
     * @param wmNews
     */
    @Override
    @Async
    public void addTask(WmNews wmNews) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(1001);
        taskDto.setPriority(1);
        taskDto.setExecuteTime(wmNews.getPublishTime().getTime());
        taskDto.setParameters(wmNews.getId().toString().getBytes());
        scheduleClient.addTask(taskDto);
    }

    /**
     * 定时拉取任务进行消费：审核文章
     * 执行频次：每秒执行一次！
     */
    @Override
    @Scheduled(cron = "*/1 * * * * ?")
    public void popTask() {
        //1. 先调用远程微服务拉取任务
        ResponseResult responseResult = scheduleClient.poll(1001, 1);
        //2. 获取任务中携带的数据
        String dataJSON = responseResult.getData().toString();
        if (responseResult.getCode().equals(200)&& !"null".equals(dataJSON)){
            TaskDto taskDto = JSON.parseObject(dataJSON,TaskDto.class);
            log.info("拉取到审核文章任务：任务信息为：{}",taskDto);

            //取出文章id进行审核
            byte[] parameters = taskDto.getParameters();
            String newsIdStr = new String(parameters);
            wmAutoScanService.autoScan(Integer.valueOf(newsIdStr));
        }
    }
}
